package com.hongxun.design.utils.serviceandclient;

import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.bean.ProjectItemBean;
import com.hongxun.design.bean.ScanHotBean;
import com.hongxun.design.bean.service.ClientInfo;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.socketutil.LongWriterAndReader;
import com.hongxun.design.bean.service.MessageData;
import com.hongxun.design.utils.socketutil.ReciveAndSend;

import java.io.IOException;
import java.net.Socket;

/**
 * Created by zerdoor_pc on 2016/7/24.
 */
public class ClientUtil {
    private Boolean flag = false;
    private MessageData messageData;
    ClientInfo serviceInfo;

    Context context;
    Handler clientUtilHandler;

    public ClientUtil() {
        MyLog.L(MString.service + "ClientUtil 初始化 ");
        mainflag=true;
        serviceInfo = new ClientInfo();
    }


    int ii = 0;
    String IP = "";
    Thread mainThread, sendThread, receiveThread;
    boolean mainflag=false;
    public synchronized void start(Context context,Handler mclientUtilHandler) {
        this.context = context;
        this.clientUtilHandler = mclientUtilHandler;
        IP = GetServerIpAddress();
        if (IP.equals("192.168.31.1")) {
            IP = "192.168.43.1";
        }
        receiveflag = true;
        mainThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Socket socket = null;
                try {

                    socket = new Socket(IP, Constant.prot);
                    if (mainflag){
                        mainflag=false;
                        MyLog.L(MString.service + " 读取ip=" + IP + clientUtilHandler);
                        serviceInfo.setIp(IP);
                        serviceInfo.setSocket(socket);
                        sendThread = new SendThread(socket);
                        receiveThread = new ReceiveThread(socket);
                        sendThread.start();
                        receiveThread.start();
                        handler.sendMessage(MyMessage.getMessage(0, "连接成功！"));
                        ScanHotBean bean=   new ScanHotBean(MyApp.userInfo.getUsername(), MyApp.userInfo.getAvatar(), MString.userInfo);
                        bean.setUserid(MyApp.userInfo.getUser_id());
                        sendMessage(JSON.toJSONString(bean));
                    }

                } catch (IOException e) {
                    //MyLog.L(MString.service + " 连接失败,重连:" + e.toString());
                    socket=null;
                    if (clientUtilHandler!=null)clientUtilHandler.sendEmptyMessage(1);
                    handler.sendMessage(MyMessage.getMessage(0, "连接失败,正在重连..."));
                }

            }
        });
        mainThread.start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ToastShow.showShort(context, (String) msg.obj);
            //MyLog.L(MyApp.AppName + msg.obj);
        }
    };



    /**
     * 发送线程*
     */
    class SendThread extends Thread {
        private Socket socket;

        public SendThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            while (receiveflag) {
                try {

                    Thread.sleep(3000);
                    if (!flag) {
                        if (messageData != null) {
                            MyLog.L(MyApp.AppName + "发送消息1");
                            flag = true;
                            LongWriterAndReader.writer(socket.getOutputStream(), messageData, true);
                            messageData = null;
                            flag = true;
                        } else {
                            LongWriterAndReader.writer(socket.getOutputStream(), 0, true);
                        }
                    }

                } catch (Exception e) {
                    MyLog.L(MyApp.AppName + "e=" + e.toString());
                }
            }
        }

        public String getSend() throws InterruptedException {
            Thread.sleep(3000);
            return "<SOAP-ENV:Envelope>" + System.currentTimeMillis() + "</SOAP-ENV:Envelope>";
        }
    }


    public void sendMessage(String s) {
       // handler.sendMessage(MyMessage.getMessage(0, "发送消息s:" + s));
        MyLog.L(MString.service + "  发送消息s:" + s);
        messageData = ReciveAndSend.getMessageData(1, s, "");
    }

    public void sendMessage(String path, String fileName) {
        messageData = ReciveAndSend.getMessageData(4, path, fileName);
    }

    /**
     * 接收线程*
     */

    boolean receiveflag = true;

    class ReceiveThread extends Thread {
        private Socket socket;
        long startTime;
        boolean isrecive=true;
        public ReceiveThread(Socket socket) {
            this.socket = socket;
            startTime = System.currentTimeMillis();
        }
        @Override
        public void run() {
            while (receiveflag) {
                String s="";
                try {
                      s = LongWriterAndReader.reader(socket.getInputStream(), true, isrecive, clientUtilHandler);
                } catch (Exception e) {
                    MyLog.L(MString.service + " 收到 Exception=" + e);
                }
                    if (s.equals("0")) {
                        MyLog.L(MString.service + " 收到 消息=" + s);
                        flag = false;
                        startTime = System.currentTimeMillis();
                    } else if (s.equals("-1")) {
                        if (System.currentTimeMillis()-startTime>20000){
                            startTime = System.currentTimeMillis();
                            MyLog.L(MString.service + "  溢出");
                            close();
                            try {
                                serviceInfo.setUserAvatar("");
                                serviceInfo.setUserName("");
                                serviceInfo.setUserId("");
                                clientUtilHandler.sendEmptyMessage(0);
                                clientUtilHandler.sendEmptyMessage(3);
                            }catch (Exception e){}


                        }
                    } else if (s.length() > 0) {
                        ScanHotBean bean = FastJsonUtil.getScanHotBean(s);
                        MyLog.L(MString.service + " 收到 s=" + s);

                        if (bean.getMessageType().equals(MString.userInfo)) {
                            serviceInfo.setUserAvatar(bean.getUserAvatar());
                            serviceInfo.setUserName(bean.getUserName());
                            serviceInfo.setUserId(bean.getUserid());

                            clientUtilHandler.sendEmptyMessage(0);
                        } else {
                            //存储项目信息
                            if (s.length() == 0) return;
                            ProjectItemBean b = FastJsonUtil.JsonToGetProject(bean.getMessage());
                            clientUtilHandler.sendMessage(MyMessage.getMessage(2, 0, 0, b.getProject_name()));
                            isrecive=MyApp.File.saveProjectList(bean.getMessage());
                        }
                        flag = false;
                        startTime = System.currentTimeMillis();
                    }

            }
        }
    }

    public ClientInfo getServiceInfo() {
        return serviceInfo;
    }

    public void close() {
        receiveflag = false;
        try {
            if (sendThread!=null)sendThread.interrupt();
            if (receiveThread!=null) receiveThread.interrupt();
        }catch (Exception e){
            MyLog.L(MString.service + " 异常 Exception=" + e);
        }

    }


    /**
     * 得到服务器的ip*
     */
    public String GetServerIpAddress() {
        WifiManager wifiManage = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        DhcpInfo info = wifiManage.getDhcpInfo();
        int i = info.serverAddress;
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                ((i >> 24) & 0xFF);
    }
}
